﻿namespace JoinBox.Basal;

using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Diagnostics;

public partial class WindowsAPI
{

    [DllImport("Kernel32.dll")]
    extern static int FormatMessage(int flag, ref IntPtr source, int msgid, int langid, ref string? buf, int size, ref IntPtr args);

    /// <summary>
    /// 获取系统错误信息描述
    /// </summary>
    /// <returns></returns>
    public static string? GetSysErrMsg()
    {
        return GetSysErrMsg(Marshal.GetLastWin32Error());
    }

    /// <summary>
    /// 获取最后一次错误码
    /// </summary>
    /// <returns></returns>
    [DllImport("kernel32.dll")]
    public static extern uint GetLastError();

    /// <summary>
    /// 获取系统错误信息描述,这里可以直接输出信息,就不用原生错误码的那个了
    /// </summary>
    /// <param name="functionName">填入监测的函数名称</param>
    /// <param name="writeErrorMessage">输出提示吗?</param>
    /// <returns>0为正确执行</returns>
    public static uint GetLastError(string functionName, bool writeErrorMessage = true)
    {
        var errorNum = GetLastError();
        if (writeErrorMessage)
        {
            var error = GetSysErrMsg();
            if (error is not null && !error.Contains("操作成功完成"))
            {
                var sb = new StringBuilder();
                sb.Append("函数:");
                sb.Append(functionName);
                sb.Append("->错误码:");
                sb.Append(errorNum);
                sb.Append("->错误信息:");
                sb.Append(error);
                Debug.WriteLine(sb);
            }
        }
        return errorNum;
    }

    /// <summary>
    /// 获取系统错误信息描述
    /// </summary>
    /// <param name="errCode">系统错误码</param>
    /// <returns></returns>
    public static string? GetSysErrMsg(int errCode)
    {
        IntPtr tempptr = IntPtr.Zero;
        string? msg = null;
        FormatMessage(0x1300, ref tempptr, errCode, 0, ref msg, 255, ref tempptr);
        return msg;
    }
}
